package controllers;

import models.roleAndPermessions.Permeission;
import play.libs.Json;
import play.mvc.*;

import views.html.*;

import java.util.ArrayList;
import java.util.List;

/**
 * This controller contains an action to handle HTTP requests
 * to the application's home page.
 */
public class HomeController extends Controller {

    /**
     * An action that renders an HTML page with a welcome message.
     * The configuration in the <code>routes</code> file means that
     * this method will be called when the application receives a
     * <code>GET</code> request with a path of <code>/</code>.
     */
    public static Result index() {

        /*List sourceList=changeListToTree();
        if (sourceList!=null && !sourceList.isEmpty()){
            session().put("roleResource",Json.toJson(sourceList).toString());
        }else {
            return ok("无权限访问该页面");
        }
        System.out.println(Json.toJson(sourceList).toString());*/
        return ok(index.render("this is the first page"));
    }

    /**
     * 转换权限数据为json格式
     * @return
     */
    public static Result changeListToTree(){
        List<List<Permeission>> list =Permeission.findEveLevelL();
        List sourceList = new ArrayList();
        int length =list.size();
        if (length>=1){
            List<Permeission> rootNodes =  list.get(0);//根节点
            for (Permeission onePer:rootNodes){
                int oneGrade =onePer.grade;
                if (oneGrade<length){//说明不是等级最低的子节点，否则是
                    sourceAddChild(list,onePer);
                }
                sourceList.add(onePer);
            }

        }
       /* return  sourceList;*/
        return  ok(Json.toJson(sourceList).toString());
    }

    /**
     * 考察知识点：引用类型实际参数的变化影响形式参数，因为传递的是地址值，所以此处返回值可以为void
     * @param size   权限等级list的长度
     * @param lastId  父节点的id
     * @param grade  权限等级
     * @param list    权限等级list
     * @param lastPer 节点对象
     */
    public static void sourceAddChild(List<List<Permeission>> list,Permeission lastPer){
        int size = list.size();
        int grade =lastPer.grade;
        if (grade<size){
            List<Permeission> nextNodes =  list.get(grade);
            for (Permeission nextPer:nextNodes){
                String nextParent = nextPer.parent;
                if (lastPer.id.equals(nextParent)){
                    sourceAddChild(list,nextPer);//调用自身方法添加节点下的子节点
                    lastPer.children.add(nextPer);
                }
            }
        }

    }




}
